package com.atguigu.crowd.handler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.atguigu.crowd.api.MySQLRemoteService;
import com.atguigu.crowd.config.OSSProperties;
import com.atguigu.crowd.constant.CrowdConstant;
import com.atguigu.crowd.entity.vo.DetailProjectVO;
import com.atguigu.crowd.entity.vo.MemberConfirmInfoVO;
import com.atguigu.crowd.entity.vo.MemberLauchInfoVO;
import com.atguigu.crowd.entity.vo.MemberLoginVO;
import com.atguigu.crowd.entity.vo.PortalProjectVO;
import com.atguigu.crowd.entity.vo.ProjectVO;
import com.atguigu.crowd.entity.vo.ReturnVO;
import com.atguigu.crowd.entity.vo.TagVO;
import com.atguigu.crowd.entity.vo.TypeVO;
import com.atguigu.crowd.util.CrowdUtil;
import com.atguigu.crowd.util.ResultEntity;
import com.github.pagehelper.PageInfo;

@Controller
public class ProjectConsumerHandler {
	
	@Autowired
	private OSSProperties ossProperties;
	
	@Autowired
	private MySQLRemoteService mySQLRemoteService;
	
	//根据排序条件分页搜索项目
	@RequestMapping("/get/project/orderby/page")
	public String listProjectOrderBy(
			@RequestParam(value="pageNum",defaultValue="1") Integer pageNum,
			@RequestParam(value="pageSize",defaultValue="12") Integer pageSize,
			@RequestParam(value="keyword",defaultValue="") String keyword,
			@RequestParam(value="factor") String factor,
			Model model) {
		PageInfo<PortalProjectVO> pageInfo = mySQLRemoteService.showProjectOrderByRemote(pageNum,pageSize,keyword,factor);
		ResultEntity<List<TypeVO>> resultEntity = mySQLRemoteService.getProjectTypeVORemote();
		if (ResultEntity.SUCCESS.equals(resultEntity.getResult())) {
			List<TypeVO> typeList = resultEntity.getData();
			model.addAttribute("typeList", typeList);
		}
		model.addAttribute(CrowdConstant.ATTR_NAME_PAGE_INFO, pageInfo);
		return "projects";
	}

	//根据状态分页搜索项目
	@RequestMapping("/get/project/by/status/page")
	public String listProjectByStatus(
			@RequestParam(value="pageNum",defaultValue="1") Integer pageNum,
			@RequestParam(value="pageSize",defaultValue="12") Integer pageSize,
			@RequestParam(value="keyword",defaultValue="") String keyword,
			@RequestParam("status") Integer status,
			Model model) {
		PageInfo<PortalProjectVO> pageInfo = mySQLRemoteService.showProjectByStatusRemote(pageNum,pageSize,keyword,status);
		ResultEntity<List<TypeVO>> resultEntity = mySQLRemoteService.getProjectTypeVORemote();
		if (ResultEntity.SUCCESS.equals(resultEntity.getResult())) {
			List<TypeVO> typeList = resultEntity.getData();
			model.addAttribute("typeList", typeList);
		}
		model.addAttribute(CrowdConstant.ATTR_NAME_PAGE_INFO, pageInfo);
		return "projects";
	}
	
	//根据分类分页搜索项目
	@RequestMapping("/get/project/by/type/page")
	public String listProjectByType(
			@RequestParam(value="pageNum",defaultValue="1") Integer pageNum,
			@RequestParam(value="pageSize",defaultValue="12") Integer pageSize,
			@RequestParam(value="keyword",defaultValue="") String keyword,
			@RequestParam("typeId") Integer typeId,
			Model model) {
		PageInfo<PortalProjectVO> pageInfo = mySQLRemoteService.showProjectByTypeIdRemote(pageNum,pageSize,keyword,typeId);
		ResultEntity<List<TypeVO>> resultEntity = mySQLRemoteService.getProjectTypeVORemote();
		if (ResultEntity.SUCCESS.equals(resultEntity.getResult())) {
			List<TypeVO> typeList = resultEntity.getData();
			model.addAttribute("typeList", typeList);
		}
		model.addAttribute(CrowdConstant.ATTR_NAME_PAGE_INFO, pageInfo);
		return "projects";
	}
	
	
	//分页搜索项目
	@RequestMapping("/get/all/project/page")
	public String listProject(
			@RequestParam(value="pageNum",defaultValue="1") Integer pageNum,
			@RequestParam(value="pageSize",defaultValue="12") Integer pageSize,
			@RequestParam(value="keyword",defaultValue="") String keyword,
			Model model) {
			
		PageInfo<PortalProjectVO> pageInfo = mySQLRemoteService.showProjectsRemote(pageNum,pageSize,keyword);
		ResultEntity<List<TypeVO>> resultEntity = mySQLRemoteService.getProjectTypeVORemote();
		if (ResultEntity.SUCCESS.equals(resultEntity.getResult())) {
			List<TypeVO> typeList = resultEntity.getData();
			model.addAttribute("typeList", typeList);
		}
		model.addAttribute(CrowdConstant.ATTR_NAME_PAGE_INFO, pageInfo);
		model.addAttribute("keyword", keyword);
		
		return "projects";
	}
	
	
	//查询项目分类和项目标签
	@RequestMapping("/launch/project/page")
	public String getProjectTypeAndTagRemote(Model model) {
		ResultEntity<List<TypeVO>> typeResultEntity = mySQLRemoteService.getProjectTypeVORemote();
		ResultEntity<List<TagVO>> tagResultEntity = mySQLRemoteService.getProjectTagVORemote();
		if (ResultEntity.SUCCESS.equals(typeResultEntity.getResult())) {
			List<TypeVO> typeList = typeResultEntity.getData();
			model.addAttribute("typeList", typeList);
		}
		if (ResultEntity.SUCCESS.equals(tagResultEntity.getResult())) {
			List<TagVO> tagList = tagResultEntity.getData();
			model.addAttribute("tagList", tagList);
		}
		return "project-launch";
	}
	//项目详情
	@RequestMapping("/get/project/detail/{projectId}")
	public String getDetailProjectRemote(@PathVariable("projectId") Integer projectId,ModelMap model){
		ResultEntity<DetailProjectVO> resultEntity = mySQLRemoteService.getDetailProjectVORemote(projectId);
		ResultEntity<MemberLauchInfoVO> launchResultEntity = mySQLRemoteService.getLaunchInfoVORemote(projectId);
		if(ResultEntity.SUCCESS.equals(resultEntity.getResult())) {
			DetailProjectVO detailProjectVO = resultEntity.getData();
			model.addAttribute("detailProjectVO", detailProjectVO);
		}
		if(ResultEntity.SUCCESS.equals(launchResultEntity.getResult())) {
			MemberLauchInfoVO memberLauchInfoVO = launchResultEntity.getData();
			model.addAttribute("memberLauchInfoVO", memberLauchInfoVO);
		}
		
		return "project-detail";
		
	}
	
	//保存确定信息
	@RequestMapping("/create/confirm")
	public String saveConfirm(
			HttpSession session,
			MemberConfirmInfoVO memberConfirmInfoVO,
			ModelMap modelMap){
		//从session中获取临时projectVO
		ProjectVO projectVO = (ProjectVO)session.getAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);
		if (projectVO==null) {
			throw new RuntimeException(CrowdConstant.MESSAGE_TEMPLE_PROJECT_MISSING);
		}
		//将memberConfirmInfoVO存入projectVO中
		projectVO.setMemberConfirmInfoVO(memberConfirmInfoVO);
		//从session中获取登录会员对象
		MemberLoginVO loginMember = (MemberLoginVO)session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);
		//获取会员id
		Integer memberId = loginMember.getId();
		//调用远程方法保存项目对象,需要会员id
		ResultEntity<String> confirmResultEntity = mySQLRemoteService.saveProjectVORemote(projectVO,memberId);
		if (ResultEntity.FAILED.equals(confirmResultEntity.getResult())) {
			modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, confirmResultEntity.getMessage());
			return "project-confirm";
		}
		//保存成功需要把session域中的临时对象移除
		session.removeAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);
		return "redirect:http://localhost/project/create/success";
	}
	
	//保存回报信息
	@ResponseBody
	@RequestMapping("/create/save/return.json")
	public ResultEntity<String> saveReturn(ReturnVO returnVO,HttpSession session){
		try {
			//从session中获取临时projectVO
			ProjectVO projectVO = (ProjectVO)session.getAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT);
			//获取回报集合
			List<ReturnVO> returnVOList = projectVO.getReturnVOList();
			if (returnVOList==null || returnVOList.size()==0) {
				returnVOList = new ArrayList<>();
				projectVO.setReturnVOList(returnVOList);
			}
			//将回报对象加入回报集合
			returnVOList.add(returnVO);
			//将临时项目对象projectVO存入sessionzhong
			session.setAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT, projectVO);
			return ResultEntity.successWithoutData();
		} catch (Exception e) {
			e.printStackTrace();
			return ResultEntity.failed(e.getMessage());
		}
		
		
	}
	
	//上传回报图片
	@ResponseBody
	@RequestMapping("/create/upload/return/picture.json")
	public ResultEntity<String> uploadReturnPicture(@RequestParam("returnPicture") MultipartFile returnPicture) throws IOException{
		
		//获取回报图片的路径
		ResultEntity<String> returnPictureResultEntity = CrowdUtil.uploadFileToOss(
				ossProperties.getEndPoint(),
				ossProperties.getAccessKeyId(),
				ossProperties.getAccessKeySecret(),
				returnPicture.getInputStream(),
				ossProperties.getBucketName(),
				ossProperties.getBucketDomain(),
				returnPicture.getOriginalFilename());
		
		return returnPictureResultEntity;
	}
	
	//保存项目基本信息
	@RequestMapping("/create/project/information")
	public String saveProjectBasicInfo(
			ProjectVO projectVO,
			//头图
			MultipartFile headerPicture,
			//详情图
			List<MultipartFile> detailPictureList,
			//临时存储对象
			HttpSession session,
			ModelMap modelMap
			) throws IOException {
		//1:头图上传
		//判断头图
		if (headerPicture.isEmpty()) {
			modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_HEADER_PIC_EMPTY);
			return "project-launch";
		}
		ResultEntity<String> headerPictureResultEntity = CrowdUtil.uploadFileToOss(
				ossProperties.getEndPoint(),
				ossProperties.getAccessKeyId(),
				ossProperties.getAccessKeySecret(),
				headerPicture.getInputStream(),
				ossProperties.getBucketName(),
				ossProperties.getBucketDomain(),
				headerPicture.getOriginalFilename());
		if (ResultEntity.FAILED.equals(headerPictureResultEntity.getResult())) {
			modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_HEADER_PIC_UPLOAD_FAILED);
			return "project-launch";
		}else {//上传成功
			String headerPicturePath = headerPictureResultEntity.getData();
			projectVO.setHeaderPicturePath(headerPicturePath);
		}
		//2:上传详情图
		List<String> detailPicturePathList = new ArrayList<String>();
		//判断详情图
		if (detailPictureList==null || detailPictureList.size()==0) {
			modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_DETAIL_PIC_EMPTY);
			return "project-launch";
		}
		//遍历详情图列表
		for (MultipartFile detailPicture : detailPictureList) {
			if(detailPicture.isEmpty()) {
				modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_DETAIL_PIC_EMPTY);
				return "project-launch";
			}
			ResultEntity<String> detailPictureResultEntity = CrowdUtil.uploadFileToOss(
					ossProperties.getEndPoint(),
					ossProperties.getAccessKeyId(),
					ossProperties.getAccessKeySecret(),
					detailPicture.getInputStream(),
					ossProperties.getBucketName(),
					ossProperties.getBucketDomain(),
					detailPicture.getOriginalFilename());
			if (ResultEntity.FAILED.equals(detailPictureResultEntity.getResult())) {
				modelMap.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_DETAIL_PIC_UPLOAD_FAILED);
				return "project-launch";
			}else {//上传成功
				String detailPicturePath = detailPictureResultEntity.getData();
				detailPicturePathList.add(detailPicturePath);
			}
		}
		//把详情图列表放入实体对象中
		projectVO.setDetailPicturePathList(detailPicturePathList);
		//3:将实体对象存入临时session域中
		session.setAttribute(CrowdConstant.ATTR_NAME_TEMPLE_PROJECT, projectVO);
		//经过zuul入口的路径需要完整访问路径
		return "redirect:http://localhost/project/return/info/page";
	}

}
